package com.xinke.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
// 扫描目标数据库的Mapper接口（包路径与源库区分）
@MapperScan(
        basePackages = "com.xinke.mapper.target",  // 目标库Mapper所在包
        sqlSessionFactoryRef = "targetSqlSessionFactory", // 关联目标库的SqlSessionFactory
        sqlSessionTemplateRef = "targetSqlSessionTemplate"
)
public class TargetDbConfig {

    // 目标库的SqlSessionFactory
    @Bean(name = "targetSqlSessionFactory")
    public MybatisSqlSessionFactoryBean targetSqlSessionFactory(
            @Qualifier("targetDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        // 目标库Mapper的XML路径（可选）
        sessionFactory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mapper/target/*.xml")
        );
        // 配置分页插件
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        sessionFactory.setPlugins(interceptor);
        return sessionFactory;
    }

    @Bean("targetSqlSessionTemplate")
    public SqlSessionTemplate targetSqlSessionTemplate(
            @Qualifier("targetSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}